import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Redirect, Switch } from "react-router-dom";
import { Layout, Menu, Icon, Table, Button, Form, DatePicker, Input, Dropdown, Tag, Drawer, Collapse, Tabs, Card, Row, Col, List, Alert } from "antd";
// import { Descriptions } from 'antd';
import moment from 'moment';
import { listMenuByPermission } from "../js/api.js";
import icon from "../img/icon.png";
import { getEduInspectConditionApi, getEduInspectConditionByChildDepartmentIdApi, getEduInspectConditionBySymbolApi, getEduInspectConditionByItemApi } from "../js/eduInspectapi.js";

import { iconFontUrl } from "../js/config.js";

const IconFont = Icon.createFromIconfontCN({
    scriptUrl: iconFontUrl,
});

const { Content, Footer, Sider, Header } = Layout;

const FormItem = Form.Item;

const { Panel } = Collapse;

const { TabPane } = Tabs;

const { Meta } = Card;

class EdudepartmentSchoolSafetySupervisor extends Component {
    constructor(props) {
        super(props);
        let url = document.location.href;
        let page = url.split("/")[5];
        let defaultSelectedKeys;
        switch (page) {
            case "inspectReport":
                defaultSelectedKeys = "inspectReport"; break;
            default: defaultSelectedKeys = "inspectReport";
        }
        this.state = {
            defaultSelectedKeys: [defaultSelectedKeys],
            collapsed: false,
            menuData: []
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        let departmentId = sessionStorage.getItem("departmentId");
        let identityId = sessionStorage.getItem("identityId");
        listMenuByPermission(departmentId, identityId)
            .then(res => {
                this.setState({
                    menuData: res.data
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    onCollapse = (collapsed) => {
        //console.log(collapsed);
        if (collapsed) {
            document.getElementById("logoName").style.display = "none";
        } else {
            document.getElementById("logoName").style.display = "inline";
        }
        this.setState({ collapsed });
    }

    logOff() {
        sessionStorage.setItem("username", null);
        sessionStorage.setItem("identityId", null);
        sessionStorage.setItem("departmentId", null);
        this.props.history.push("/");
    }

    render() {
        const menu = this.state.menuData.map(val => {
            const subMenu = val.subMenu.map(subVal => {
                return (
                    <Menu.Item key={subVal.key}>
                        <Link to={subVal.route}>
                            <IconFont type={subVal.icon} className='icon' />
                            <span className="nav-text">{subVal.name}</span>
                        </Link>
                    </Menu.Item>
                )
            });
            return (
                val.subMenu.length == 0 ?
                    (
                        <Menu.Item key={val.key}>
                            <Link to={val.route}>
                                <IconFont type={val.icon} className='icon' />
                                <span className="nav-text">{val.name}</span>
                            </Link>
                        </Menu.Item>
                    ) :
                    (
                        <SubMenu
                            key={val.key}
                            title={
                                <span>
                                    <IconFont type={val.icon} className='icon' />
                                    <span>{val.name}</span>
                                </span>
                            }>
                            {subMenu}
                        </SubMenu>
                    )
            );
        });
        return (
            <Router basename="/edudepartment/ssv">
                <Layout>
                    <Sider
                        collapsible
                        collapsed={this.state.collapsed}
                        onCollapse={this.onCollapse}
                        width={256}
                        style={{
                            overflow: "auto",
                            height: "100vh",
                            left: 0
                        }}>
                        <div className="logo" >
                            {/* <IconFont type="icon-anfang" className='icon' style={{ verticalAlign: "middle", }} /> */}
                            <img src={icon} className='icon' style={{
                                verticalAlign: 'middle',
                                width: '30px',
                                height: '30px',
                                marginRight: '5px'
                            }} />
                            <div
                                id='logoName'
                                style={{ verticalAlign: 'middle', display: 'inline-block', paddingLeft: "5px" }}>
                                梯度智慧安监
                            </div>
                        </div>
                        <Menu theme="dark" mode="inline" defaultSelectedKeys={this.state.defaultSelectedKeys}>
                            {menu}
                        </Menu>
                    </Sider>
                    <Layout style={{ height: "100vh" }}>
                        <Header style={{
                            background: '#fcfcfc',
                            padding: 0,
                            fontFamily: 'Microsoft Yahei, sans-serif',
                            fontSize: 15,
                            position: 'relative',
                            height: '64px',
                            lineHeight: '64px',
                        }}>
                            <div style={{ position: "absolute", top: 0, bottom: 0, left: 24, }}>
                                欢迎您！您的身份为<span style={{ color: '#1890ff' }}>教育局安监处</span>
                            </div>
                            <div style={{ position: "absolute", top: 0, bottom: 0, right: 24, }}>
                                <Dropdown overlay={
                                    <Menu>
                                        <Menu.Item>
                                            <a
                                                class='logOff'
                                                style={{ color: '#333333', padding: '5px 15px' }}
                                                onClick={() => this.logOff()}>
                                                <IconFont
                                                    type="icon-zhuxiaologout11" className='icon'
                                                    style={{ fontSize: '14px', verticalAlign: 'middle' }} />
                                                <span style={{ verticalAlign: 'middle', marginLeft: '2px' }}>退出登录</span>
                                            </a>
                                        </Menu.Item>
                                    </Menu>
                                }>
                                    <div
                                        className='dropdown'
                                        style={{
                                            padding: '0px 5px'
                                        }}>
                                        <IconFont
                                            style={{ fontSize: '28px', verticalAlign: 'middle' }}
                                            type="icon-touxiang-shi" className='icon' />
                                        <span style={{ marginLeft: '2px' }}>{sessionStorage.getItem("username")}</span>
                                    </div>
                                </Dropdown>
                            </div>
                        </Header>
                        <Content style={{ margin: "24px", overflow: "initial" }}>
                            <div
                                id="right"
                                style={{
                                    padding: 24,
                                    background: "#fff",
                                    height: "auto",
                                    marginBottom: 24
                                }}
                            >
                                <Switch>
                                    <Route path="/inspectReport" component={EduDepartmentInspect} />
                                    <Redirect path="/" to={{ pathname: '/inspectReport' }} />
                                </Switch>
                            </div>
                        </Content>
                        {/* <Footer style={{ textAlign: "center", background: '#fcfcfc', }}>绍兴市教育局</Footer> */}
                    </Layout>
                </Layout>
            </Router>
        );
    }
}

class EduDepartmentInspect extends Component {
    constructor(props) {
        super(props);

        this.state = {
            drawerVisible: false,
            msg: "", //提交失败时的提示语
            tableLoading: false,
            filteredInfo: null,
            sortedInfo: null,
            data: [],
            searchText: '',
        };
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        getEduInspectConditionApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        id: item.id,
                        childDepartment: item.childDepartment,
                        type: item.type ? "蓝牙模式" : "无蓝牙模式",
                        times: item.times,
                    });
                });
                this.setState({
                    columnData: columnData,
                    tableLoading: false,
                });
                this.child.refreshData();
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    showInspect = (symbol) => {
        this.setState({
            drawerVisible: true,
            symbol: symbol,
        })
    }


    onClose = () => {
        this.setState({
            drawerVisible: false,
        });
    };

    handleChange = (pagination, filters, sorter) => {
        //console.log('Various parameters', pagination, filters, sorter);
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
        this.setState({
            searchText: selectedKeys[0],
        });
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
        this.setState({
            searchText: '',
        });
    }

    render() {
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const columDate2 = this.state.columnData2;
        const columns1 = [
            {
                title: "序号",
                dataIndex: "key",
                key: "key"
            },
            {
                title: "学校名称",
                dataIndex: "childDepartment",
                key: "childDepartment",
                filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                    <div className="custom-filter-dropdown">
                        <Input
                            ref={ele => this.searchInput = ele}
                            value={selectedKeys[0]}
                            onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                            onPressEnter={this.handleSearch(selectedKeys, confirm)}
                        />
                        <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                        <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                    </div>
                ),
                filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
                onFilter: (value, record) => record.childDepartment.toLowerCase().includes(value.toLowerCase()),
                onFilterDropdownVisibleChange: (visible) => {
                    if (visible) {
                        setTimeout(() => {
                            this.searchInput.focus();
                        });
                    }
                }
            },
            {
                title: "巡检类型",
                key: "type",
                render: (text, record) => {
                    let color;
                    const color1 = "blue";
                    const color2 = "grey";
                    if (record.type === "蓝牙模式") { color = color1; }
                    else { color = color2; }
                    return (
                        <Tag color={color} width={30}>{record.type}</Tag>
                    )
                }
            },
            {
                title: "总抽检次数",
                dataIndex: "times",
                key: "times",
            },
        ];

        return (
            <div>
                <Drawer
                    title="巡检详情"
                    placement="right"
                    closable={false}
                    onClose={this.onClose}
                    visible={this.state.drawerVisible}
                    width={720}
                    bodyStyle={{
                        height: "100%"
                    }}
                >
                    <Layout
                        style={{
                            background: "#FFFFFF",
                            height: "100%"
                        }}>
                        <Content>
                            <InspectConditionTags
                                symbol={this.state.symbol}
                            />
                        </Content>
                        <Footer style={{
                            background: "#FFFFFF",
                            height: "15%",
                            bottom: 0,
                        }}>
                            <Alert
                                style={{
                                    bottom: "0px"
                                }}
                                message="未通过和通过的卡片可以点击跳转查看详情，未完成的卡片无法点击跳转" type="info" showIcon />
                        </Footer>
                    </Layout>
                </Drawer>
                <Table
                    dataSource={this.state.columnData}
                    columns={columns1}
                    className="components-table-demo-nested"
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    onChange={this.handleChange}
                    rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                    expandedRowRender={(record) => {
                        return (
                            <InspectConditionTable
                                childDepartmentId={record.id}
                                showInspect={this.showInspect} />)
                    }}
                    pagination={{  //分页
                        total: this.state.data.length, //数据总数量
                        defaultPageSize: 10, //默认显示几条一页
                        //pageSize: 10,
                        showTotal: function (total) {  //设置显示一共几条数据
                            return '共 ' + total + ' 条数据';
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: [5, 10, 20, 30]
                    }} />
            </div>
        )
    }
}

class InspectConditionTable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            childDepartmentId: props.childDepartmentId,
            tableLoading: false,
            columnData: [],
        }
    }

    inspectCondition = (record) => {
        this.props.showInspect(record.symbol);
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        let columnData = [];
        getEduInspectConditionByChildDepartmentIdApi(parseInt(sessionStorage.getItem("departmentId")), this.state.childDepartmentId)
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        date: item.date,
                        time: item.startDate + "~" + item.endDate,
                        status: item.status,
                        symbol: item.symbol,
                    });
                });
                this.setState({
                    columnData: columnData,
                    tableLoading: false,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    render() {
        const columns2 = [
            {
                title: "日期",
                dataIndex: "date",
                key: "date"
            },
            {
                title: "时间段",
                dataIndex: "time",
                key: "time",
            },
            {
                title: "巡检情况",
                key: "status",
                render: (text, record) => {
                    let color;
                    let status;
                    if (record.status === "4") {
                        color = "magenta";
                        status = "未通过";
                    } else {
                        color = "green";
                        status = "全部通过";
                    }

                    return (<Tag href="javascript:;" color={color}>{status}</Tag>)
                }
            },
            {
                title: "操作",
                key: "action",
                render: (text, record) => {
                    return (<a href="javascript:;" onClick={() => this.inspectCondition(record)}>查看详情</a>)
                }
            },
        ];
        return (
            <Table
                columns={columns2}
                dataSource={this.state.columnData}
                pagination={false}
                locale={{ emptyText: '暂无数据' }}
                rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                bordered={true}
                loading={this.state.tableLoading}
                size='small'
            />)
    }
}

class InspectConditionTags extends Component {
    constructor(props) {
        super(props);
        console.log(props);
        this.state = {
            symbol: props.symbol,
            columnData: [],
            visible: false,
            item: "",
        }
    }

    componentDidMount() {
        let columnData = [];
        getEduInspectConditionBySymbolApi(this.state.symbol, parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        category: item.category,
                        categoryId: item.categoryId,
                        itemList: item.itemList,
                        status: item.status,
                    });
                });
                this.setState({
                    columnData: columnData,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    click = (item, status) => {
        if (status === "3" || status === "4") {
            this.setState({
                item: item,
                visible: true,
            });
        }

    }

    onClose = () => {
        this.setState({
            visible: false,
        });
    };

    render() {

        const { columnData } = this.state;
        const panlList = [];

        const isDoneIcon = (status) => (status === "3" ? <IconFont type="icon-tongguo" className='icon' /> : <IconFont type="icon-weitongguo" className='icon' />);
        const isDoneWord = (status) => {
            if (status === "3") { return "全部通过"; }
            else if (status === "4") { return "未通过"; }
            else if (status === "0") { return "未完成"; }
        };
        const style = (status) => (status === "0" ? {
            marginTop: 16,
            width: "80%",
            textAlign: "-webkit-left",
            cursor: "auto",
        } :
            {
                marginTop: 16,
                width: "80%",
                textAlign: "-webkit-left",
                cursor: "pointer",
                boxShadow: "5px 5px 5px #285a63",
            })

        for (let i = 0; i < columnData.length; i++) {
            let itemList = columnData[i].itemList;
            let pannl2 = itemList.map((d, index) =>
                <Col span={12} style={{ textAlign: "-webkit-center" }}>
                    <Card
                        style={style(d.status)}
                        type="inner"
                        key={index}
                        loading={false}
                        onClick={() => this.click(d.item, d.status)}>
                        <Row type="flex" justify="space-around" align="middle">
                            <Col span={6} align="left">{isDoneIcon(d.status)}</Col>
                            <Col span={18}>
                                <Meta
                                    title={d.item}
                                    description={isDoneWord(d.status)}
                                >
                                </Meta></Col>
                        </Row>
                    </Card>
                </Col>);
            panlList.push(pannl2);
        }
        const Tabpanel1 = columnData.map((d, index) =>
            <TabPane
                tab={
                    <span>
                        {isDoneIcon(d.status)}
                        {d.category}
                    </span>
                }
                key={d.key}>
                <Row gutter={36}>
                    {panlList[d.key - 1]}
                </Row>
            </TabPane>);

        return (
            <div>
                <Drawer
                    title={this.state.item + "——巡检细则"}
                    placement="right"
                    closable={false}
                    onClose={this.onClose}
                    visible={this.state.visible}
                    destroyOnClose={true}
                    width={480}
                >
                    <InspectConsitionContentCollapse
                        symbol={this.state.symbol}
                        item={this.state.item}
                    />
                </Drawer>
                <Tabs defaultActiveKey="1">
                    {Tabpanel1}
                </Tabs>
            </div>
        )
    }
}

class InspectConsitionContentCollapse extends Component {
    constructor(props) {
        super(props);
        this.state = {
            symbol: props.symbol,
            item: props.item,
            columnData: [],
        }
        console.log(this.state.item);
    }

    componentDidMount() {
        let columnData = [];
        getEduInspectConditionByItemApi(this.state.symbol, this.state.item)
            .then((res) => {
                res.data.forEach((item, index) => {
                    columnData.push({
                        key: index + 1,
                        date: item.date,
                        record: item.record,
                        picture: item.picture,
                        content: item.content,
                        status: item.status,
                        name: item.name,
                        visable: item.status === "4" ? false : true,
                    });
                });
                this.setState({
                    columnData: columnData,
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    render() {
        const { columnData } = this.state;
        const list = [];

        const isDoneIcon = (status) => (status === "3" ? <IconFont type="icon-tongguo" className='icon' /> : <IconFont type="icon-weitongguo" className='icon' />);
        const isDoneWord = (status) => {
            if (status === "3") { return "全部通过"; }
            else if (status === "4") { return "未通过"; }
            else if (status === "0") { return "未完成"; }
        };

        const customPanelStyle = {
            background: '#f7f7f7',
            borderRadius: 8,
            marginBottom: 24,
            border: 0,
            overflow: 'hidden',
        };

        const MetaStyle = {
            paddingLeft: "10px",
            background: '#FFF',
            marginTop: "10px",
            borderRadius: 8,
        };

        const panel = columnData.map((d, index) =>
            <Panel
                style={customPanelStyle}
                header={
                    <div>
                        <Row type="flex" justify="space-around" align="middle">
                            <Col span={20}><div>{d.content}</div></Col>
                            <Col span={4} align="right">{isDoneIcon(d.status)}</Col>
                        </Row>
                    </div>
                }
                key={d.key}
                disabled={d.visable}>
                <List
                    loading={false}
                    itemLayout="horizontal"
                >
                    <List.Item
                        style={MetaStyle}>
                        <List.Item.Meta
                            title={<a>巡检时间</a>}
                            description={d.date}
                        />
                    </List.Item>
                    <List.Item
                        style={MetaStyle}>
                        <List.Item.Meta
                            title={<a>巡检状况</a>}
                            description={isDoneWord(d.status)}
                        />
                    </List.Item>
                    <List.Item
                        style={MetaStyle}>
                        <List.Item.Meta
                            title={<a>巡检人</a>}
                            description={d.name}
                        />
                    </List.Item>
                    <List.Item
                        style={MetaStyle}>
                        <List.Item.Meta
                            title={<a>描述</a>}
                            description={d.record}
                        />
                    </List.Item>
                    <List.Item
                        style={MetaStyle}>
                        <List.Item.Meta
                            title={<a>图片</a>}
                            description={d.picture}
                        />
                    </List.Item>
                </List>
            </Panel>
        );

        return (
            <Collapse
                bordered={false}
                expandIcon={({ isActive }) => <Icon type="caret-right" rotate={isActive ? 90 : 0} />}
            >
                {panel}
            </Collapse>
        )
    }
}

export default EdudepartmentSchoolSafetySupervisor;
export { EduDepartmentInspect }